import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import nested from '@/views/nested'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function urlTranslateName(url) {
  return url.split('/').pop()
}
export function filterAsyncRoutes(menus) {
  const res = []
  menus.forEach(route => {
    // 排除按钮
    if (route.type === 0 || route.type === 1) {
      let component = Layout
      if (route.type == 0 && route.parentId != '0') {
        component = nested
      } else if (route.componentPath) {
        component = resolve => {
          require([`@/views/${route.componentPath}`], resolve)
        }
      }
      const tmp = {
        path: route.url,
        name: route.urlAlias,
        meta: { title: route.name, icon: route.icon, menuId: route.menuId, type: route.type },
        component: component,
        type: route.type,
        children: []
      }
      if (route.list) {
        tmp.children = filterAsyncRoutes(route.list)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menus = []) {
    return new Promise(resolve => {
      let accessedRoutes = []
      accessedRoutes = generateRoute(menus)
      accessedRoutes = accessedRoutes.concat(asyncRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export function generateRoute(menus) {
  const route = []
  for (let index = 0; index < menus.length; index++) {
    const menuItem = menus[index]
    if (menuItem.type == 0 || menuItem.type == 1) {
      // 这样二级目录无需再配置 nested/index
      let component = Layout
      if (menuItem.type == 0 && menuItem.parentId != '0') {
        component = resolve => {
          require(['@/views/nested/index'], resolve)
        }
      } else if (menuItem.componentPath && menuItem.componentPath != '') {
        component = resolve => {
          require([`@/views/${menuItem.componentPath}`], resolve)
        }
      }
      const itemData = {
        path: menuItem.url || Math.random() + '',
        name: menuItem.urlAlias,
        meta: {
          title: menuItem.name,
          icon: menuItem.icon,
          menuId: menuItem.menuId,
          type: menuItem.type
        },
        component: component,
        hidden: menuItem.type === 2,
        type: menuItem.type,
        children: [],
        parentId: menuItem.parentId
      }
      if (menuItem.list) {
        const children = generateRoute(menuItem.list)
        itemData.children = children
      }
      route.push(itemData)
    }
  }

  return route
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
